<?php
$pageTitle = '男友资料';
require_once '../../config/config.php';
require_once '../../includes/functions.php';
require_once '../../classes/User.php';
require_once '../../classes/Friend.php';
require_once '../../classes/Task.php';

// 检查用户是否登录
if (!isLoggedIn()) {
    setFlashMessage('error', '请先登录');
    redirect(SITE_URL . '/login.php');
}

$userId = $_SESSION['user_id'];
$friendId = isset($_GET['id']) ? intval($_GET['id']) : 0;

// 验证男友ID
if ($friendId <= 0) {
    setFlashMessage('error', '无效的男友ID');
    redirect(SITE_URL . '/views/friend/list.php');
}

// 获取男友信息
$db = Database::getInstance();
$friendInfo = $db->fetch("SELECT * FROM users WHERE id = ?", [$friendId]);

if (!$friendInfo) {
    setFlashMessage('error', '用户不存在');
    redirect(SITE_URL . '/views/friend/list.php');
}

// 获取男友关系
$friend = new Friend();
$isFriend = $friend->isFriend($userId, $friendId);
$friendshipStatus = $friend->getFriendshipStatus($userId, $friendId);
$friendshipId = $friend->getFriendshipId($userId, $friendId);

// 获取共同任务
$task = new Task();
$sharedTasks = [];

if ($isFriend) {
    // 获取亲密度历史
    $intimacyLogs = $friend->getIntimacyLogs($friendshipId);
    
    // 获取共同任务
    $sharedTasks = $db->fetchAll(
        "SELECT t.* FROM tasks t
         LEFT JOIN task_participants tp ON t.id = tp.task_id
         WHERE (t.creator_id = ? AND tp.user_id = ?)
            OR (t.creator_id = ? AND tp.user_id = ?)
         GROUP BY t.id
         ORDER BY t.created_at DESC
         LIMIT 5",
        [$userId, $friendId, $friendId, $userId]
    );
}

include '../../includes/header.php';
?>

<div class="container py-4">
    <div class="row">
        <div class="col-lg-4 mb-4">
            <div class="card shadow-sm">
                <div class="card-body text-center">
                    <img src="<?php echo getUserAvatar($friendInfo['avatar']); ?>" class="rounded-circle mb-3" width="120" height="120" alt="<?php echo htmlspecialchars($friendInfo['nickname'] ?: $friendInfo['username']); ?>">
                    <h4><?php echo htmlspecialchars($friendInfo['nickname'] ?: $friendInfo['username']); ?></h4>
                    <p class="text-muted"><?php echo htmlspecialchars($friendInfo['username']); ?></p>
                    
                    <?php if ($isFriend): ?>
                        <div class="d-flex align-items-center justify-content-center mb-3">
                            <div class="text-warning me-2">
                                <i class="fas fa-heart"></i>
                            </div>
                            <div class="progress flex-grow-1" style="height: 8px; max-width: 200px;">
                                <?php 
                                $intimacy = $db->fetch(
                                    "SELECT intimacy FROM friendships WHERE id = ?", 
                                    [$friendshipId]
                                )['intimacy'] ?? 0;
                                ?>
                                <div class="progress-bar bg-warning" role="progressbar" style="width: <?php echo min(100, ($intimacy / 100) * 100); ?>%" aria-valuenow="<?php echo $intimacy; ?>" aria-valuemin="0" aria-valuemax="100"></div>
                            </div>
                            <span class="ms-2"><?php echo $intimacy; ?></span>
                        </div>
                        
                        <div class="d-grid gap-2">
                            <a href="<?php echo SITE_URL; ?>/views/task/create.php?friend_id=<?php echo $friendId; ?>" class="btn btn-primary">
                                <i class="fas fa-calendar-plus"></i> 发起约定
                            </a>
                            <button type="button" class="btn btn-outline-danger delete-friend" data-id="<?php echo $friendId; ?>" data-name="<?php echo htmlspecialchars($friendInfo['nickname'] ?: $friendInfo['username']); ?>">
                                <i class="fas fa-user-times"></i> 删除男友
                            </button>
                        </div>
                    <?php elseif ($friendshipStatus === 'pending'): ?>
                        <?php if ($db->fetch("SELECT * FROM friendships WHERE user_id = ? AND friend_id = ?", [$userId, $friendId])): ?>
                            <div class="alert alert-warning">
                                <i class="fas fa-clock"></i> 男友请求已发送，等待对方接受
                            </div>
                        <?php else: ?>
                            <div class="alert alert-info">
                                <i class="fas fa-envelope"></i> 对方向您发送了男友请求
                            </div>
                            <div class="d-grid gap-2">
                                <a href="<?php echo SITE_URL; ?>/views/friend/request.php" class="btn btn-primary">查看请求</a>
                            </div>
                        <?php endif; ?>
                    <?php else: ?>
                        <form method="POST" action="<?php echo SITE_URL; ?>/api/friend/add.php">
                            <input type="hidden" name="friend_id" value="<?php echo $friendId; ?>">
                            <button type="submit" class="btn btn-primary btn-lg w-100">
                                <i class="fas fa-user-plus"></i> 添加男友
                            </button>
                        </form>
                    <?php endif; ?>
                </div>
            </div>
        </div>
        
        <div class="col-lg-8">
            <?php if ($isFriend): ?>
                <!-- 共同任务 -->
                <div class="card shadow-sm mb-4">
                    <div class="card-header">
                        <h5 class="mb-0"><i class="fas fa-tasks"></i> 共同约定</h5>
                    </div>
                    <div class="card-body">
                        <?php if (empty($sharedTasks)): ?>
                            <div class="text-center py-4">
                                <i class="fas fa-calendar-day fa-3x text-muted mb-3"></i>
                                <p class="lead">您与该男友暂无共同约定</p>
                                <a href="<?php echo SITE_URL; ?>/views/task/create.php?friend_id=<?php echo $friendId; ?>" class="btn btn-primary">
                                    <i class="fas fa-calendar-plus"></i> 发起约定
                                </a>
                            </div>
                        <?php else: ?>
                            <div class="list-group">
                                <?php foreach ($sharedTasks as $task): ?>
                                    <a href="<?php echo SITE_URL; ?>/views/task/detail.php?id=<?php echo $task['id']; ?>" class="list-group-item list-group-item-action">
                                        <div class="d-flex w-100 justify-content-between">
                                            <h6 class="mb-1"><?php echo htmlspecialchars($task['title']); ?></h6>
                                            <small class="text-<?php echo $task['status'] == 'completed' ? 'success' : ($task['status'] == 'expired' ? 'danger' : 'primary'); ?>">
                                                <?php 
                                                echo $task['status'] == 'completed' ? '已完成' : 
                                                    ($task['status'] == 'expired' ? '已过期' : '进行中'); 
                                                ?>
                                            </small>
                                        </div>
                                        <p class="mb-1 text-truncate"><?php echo htmlspecialchars($task['description']); ?></p>
                                        <small class="text-muted">截止时间: <?php echo formatDateTime($task['deadline']); ?></small>
                                    </a>
                                <?php endforeach; ?>
                            </div>
                            <div class="mt-3 text-end">
                                <a href="<?php echo SITE_URL; ?>/views/task/list.php?friend_id=<?php echo $friendId; ?>" class="btn btn-sm btn-outline-primary">
                                    查看全部约定
                                </a>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
                
                <!-- 亲密度记录 -->
                <div class="card shadow-sm">
                    <div class="card-header">
                        <h5 class="mb-0"><i class="fas fa-heart"></i> 亲密度记录</h5>
                    </div>
                    <div class="card-body">
                        <?php if (empty($intimacyLogs)): ?>
                            <div class="text-center py-4">
                                <i class="fas fa-heart-broken fa-3x text-muted mb-3"></i>
                                <p class="lead">暂无亲密度记录</p>
                                <p class="text-muted">完成约定可以增加亲密度哦</p>
                            </div>
                        <?php else: ?>
                            <div class="timeline">
                                <?php foreach ($intimacyLogs as $log): ?>
                                    <div class="timeline-item">
                                        <div class="timeline-point">
                                            <i class="fas fa-heart text-danger"></i>
                                        </div>
                                        <div class="timeline-content">
                                            <div class="d-flex justify-content-between">
                                                <h6><?php echo htmlspecialchars($log['description'] ?: '亲密度增加'); ?></h6>
                                                <span class="badge bg-warning">+<?php echo $log['points']; ?></span>
                                            </div>
                                            <?php if ($log['task_id'] && $log['task_title']): ?>
                                                <p class="mb-1">
                                                    <a href="<?php echo SITE_URL; ?>/views/task/detail.php?id=<?php echo $log['task_id']; ?>">
                                                        <?php echo htmlspecialchars($log['task_title']); ?>
                                                    </a>
                                                </p>
                                            <?php endif; ?>
                                            <small class="text-muted"><?php echo formatDateTime($log['created_at']); ?></small>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            <?php else: ?>
                <div class="card shadow-sm">
                    <div class="card-body">
                        <div class="text-center py-5">
                            <i class="fas fa-user-lock fa-3x text-muted mb-3"></i>
                            <p class="lead">成为男友后可查看更多信息</p>
                            <?php if ($friendshipStatus !== 'pending'): ?>
                                <form method="POST" action="<?php echo SITE_URL; ?>/api/friend/add.php">
                                    <input type="hidden" name="friend_id" value="<?php echo $friendId; ?>">
                                    <button type="submit" class="btn btn-primary">
                                        <i class="fas fa-user-plus"></i> 添加男友
                                    </button>
                                </form>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            <?php endif; ?>
        </div>
    </div>
</div>

<!-- 删除男友确认模态框 -->
<div class="modal fade" id="deleteFriendModal" tabindex="-1" aria-labelledby="deleteFriendModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="deleteFriendModalLabel">确认删除男友</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <p>您确定要删除 <span id="friendName"></span> 吗？</p>
                <p class="text-danger">删除后，您将失去与该男友的所有亲密度记录。</p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <form id="deleteFriendForm" method="POST" action="<?php echo SITE_URL; ?>/api/friend/delete.php">
                    <input type="hidden" name="friend_id" id="friendId">
                    <button type="submit" class="btn btn-danger">确认删除</button>
                </form>
            </div>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // 删除男友确认
    const deleteBtns = document.querySelectorAll('.delete-friend');
    const friendNameEl = document.getElementById('friendName');
    const friendIdInput = document.getElementById('friendId');
    
    deleteBtns.forEach(btn => {
        btn.addEventListener('click', function() {
            const id = this.dataset.id;
            const name = this.dataset.name;
            
            friendNameEl.textContent = name;
            friendIdInput.value = id;
            
            const modal = new bootstrap.Modal(document.getElementById('deleteFriendModal'));
            modal.show();
        });
    });
});
</script>

<style>
.timeline {
    position: relative;
    padding: 20px 0;
}

.timeline:before {
    content: '';
    position: absolute;
    top: 0;
    left: 15px;
    height: 100%;
    width: 2px;
    background: #e9ecef;
}

.timeline-item {
    position: relative;
    margin-bottom: 20px;
    padding-left: 40px;
}

.timeline-point {
    position: absolute;
    left: 0;
    width: 30px;
    height: 30px;
    border-radius: 50%;
    background: #fff;
    border: 2px solid #e9ecef;
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 1;
}

.timeline-content {
    padding: 15px;
    background: #f8f9fa;
    border-radius: 4px;
    position: relative;
}

.timeline-content:before {
    content: '';
    position: absolute;
    left: -10px;
    top: 15px;
    width: 0;
    height: 0;
    border-top: 10px solid transparent;
    border-bottom: 10px solid transparent;
    border-right: 10px solid #f8f9fa;
}
</style>

<?php include '../../includes/footer.php'; ?>
